<?php
namespace Framework\Http;

/**
 *  //基础
 *	$session->open();
 *	$session->close();
 *	$session->destroy();//销毁session
 *  
 *  //增删改查
 *	$session->all();
 *	$session->get('name');
 *	$session->set('name', '');
 *	$session->remove('name');
 *	$session->flush();//清空session
 *	
 *  //值判断
 *	$session->has('name');
 *	$session->exists('name');
 *  
 *  //遍历所有session变量
 *  foreach ($session->all() as $name => $value)
 *
 *  
 */
class Seesion
{
	//使用自定义的储存
	protected $customStorage = false;

	public function __construct()
	{
		$this->registerSessionHandler();

		$this->init();
	}

	public function init(){}

	public function registerSessionHandler()
	{
		if( $this->customStorage ){
            session_set_save_handler(
                [$this, 'openSession'],
                [$this, 'close'],
                [$this, 'read'],
                [$this, 'write'],
                [$this, 'destroy'],
                [$this, 'gc']
            );
		}
	}

    public function getIsActive() : bool
    {
        return session_status() === PHP_SESSION_ACTIVE;
    }

	public function open()
	{
        if ( !$this->getIsActive() ){
            session_start();
        }
	}

	public function get($key, $default='')
	{
		$this->open();
		return $this->exists($key) ? $_SESSION[$key] : $default ;
	}

	public function set($key, $value)
	{
        $this->open();
        $_SESSION[$key] = $value;
	}

	//获取所有 Session 数据
	public function all()
	{
        $this->open();
		return $_SESSION;
	}

	public function forget($key)
	{
        $this->open();
        if (isset($_SESSION[$key])) {
            $value = $_SESSION[$key];
            unset($_SESSION[$key]);
            return $value;
        }

        return null;
	}




	//判断 Session 中是否存在某个值  (该值存在且不为null)
	public function has($key)
	{
        $this->open();
		return isset($_SESSION[$key]) && $_SESSION[$key]!==null ;
	}

	//判断 Session 中是否存在某个值 (该值存在即使null)
	public function exists($key)
	{
        $this->open();
		return isset($_SESSION[$key]);
	}


    public function getTimeout()
    {
        return (int) ini_get('session.gc_maxlifetime');
    }



	//protected
    public function openSession($savePath, $sessionName) {
    	return true;
    }

    public function close() {
    	return true;
    }


    public function read($sessionId) {
        return '';
    }

    public function write($sessionId, $data) {
    	var_dump($sessionId);
    	return true;
    }

    public function destroy($sessionId) {
        return true;
    }

    public function gc($lifetime) {
        return true;
    }
}